/**
Copyright (c) 2009, Aspect Foundation
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/

/**
This utility converts human-readable model (.hrm) files into a format native to the Aspect Engine's
own model system. This allows it to load the models faster at run-time. The application is designed
to run stand-alone from a console and can be executed by the engine to automatically convert any
.hrm files it is asked to use. The only parameter is the relative path to the file you wish to
convert. This program will then create a new file (overwriting any existing file with the same
name) with the extention .amf (Aspect Model File).
**/

#include <iostream>
#include "../../AspectEngine/AspectEngine.h"
#include "tinyxml.h"

using namespace agtk;

void ErrorOut(char* message);
void Warn(char* message);
void ConvertModel(char* in, char* out);

int main(int argc, char* argv[]) {
	// Ensure that we only have one param.
	if (argc != 3) {
		ErrorOut("This application needs two paramerters, the path to the file you wish to convert, and a name for the converted file.");
	}
	
	char* fin = argv[1];
	char* fout = argv[2];
	
	std::cout << fin << std::endl;

	ConvertModel(fin, fout);
	
	std::cout << "Finished conversion." << std::endl;
	
	return 0;
}

void ErrorOut(char* message) {
	std::cout << "Error! - " << message << std::endl;
	exit(1);
}

void Warn(char* message) {
	std::cout << "Warning! - " << message << std::endl;
}

void ConvertModel(char* in, char* out) {
	LinkedList<Triangle> triangleList;
	ModelVersion versionData;
	ModelHeader headerData;
	
	int i = 0;
	
	versionData.version = AE_LATEST_MODEL_VERSION;
	versionData.revision = AE_LATEST_MODEL_REVISION;
	
	TiXmlDocument doc( in ); 
        bool loadOkay = doc.LoadFile();
        if ( !loadOkay ) {
                ErrorOut("Could not load file.");
        }

        TiXmlElement* modelElement = NULL;
        TiXmlElement* propertiesElement = NULL;
	TiXmlElement* titleElement = NULL;
	TiXmlElement* descriptionElement = NULL;
	TiXmlElement* authorElement = NULL;
	TiXmlElement* defaultMaterialElement = NULL;
        TiXmlElement* trianglesElement = NULL;
        TiXmlElement* triangleElement = NULL;
        TiXmlElement* vertexElement = NULL;

        modelElement = doc.FirstChildElement("imf");
        if(!modelElement) {
                ErrorOut("Could not find <imf> element.");
        } else {
                propertiesElement = modelElement->FirstChildElement("properties");
                if(propertiesElement) {
			titleElement = propertiesElement->FirstChildElement("title");
			if(titleElement) {
				headerData.title=titleElement->GetText();
			} else {
				Warn("No <title> element found.");
				headerData.title="No title.";
			}
			descriptionElement = propertiesElement->FirstChildElement("description");
			if(descriptionElement) {
				headerData.description=descriptionElement->GetText();
			} else {
				Warn("No <description> element found.");
				headerData.description="No description.";
			}
			authorElement = propertiesElement->FirstChildElement("author");
			if(authorElement) {
				headerData.author=authorElement->GetText();
			} else {
				Warn("No <author> element found.");
				headerData.author="No author.";
			}
			defaultMaterialElement = propertiesElement->FirstChildElement("defaultmaterial");
			if(defaultMaterialElement) {
				headerData.defaultMaterialName=defaultMaterialElement->Attribute("name");
				headerData.defaultMaterialPath=defaultMaterialElement->Attribute("path");
			} else {
				Warn("No <defaultmaterial> element found.");
				headerData.defaultMaterialName="NONE";
				headerData.defaultMaterialPath="NONE";
			}
                } else {
			Warn("No <properties> element found.");
		}
                trianglesElement = modelElement->FirstChildElement("triangles");
                if(!trianglesElement) {
                        ErrorOut("Could not find <triangles> element.");
                } else {        
                        triangleElement = trianglesElement->FirstChildElement("triangle");
			if(!triangleElement)
				ErrorOut("Cannot find <triangle> element.");
                        while(triangleElement) {
                                triangleList.Add(new Triangle);
                                vertexElement = triangleElement->FirstChildElement("vertex");
				i = 0;
                                while(i<3) {
                                        triangleList.GetLast()->m_vertices[i]=new Vertex(
					(float)atof(vertexElement->Attribute("posx")),
                                        (float)atof(vertexElement->Attribute("posy")),
                                        (float)atof(vertexElement->Attribute("posz")),
                                        (float)atof(vertexElement->Attribute("normx")),
                                        (float)atof(vertexElement->Attribute("normy")),
                                        (float)atof(vertexElement->Attribute("normz")),
                                        (float)atof(vertexElement->Attribute("u")),
                                        (float)atof(vertexElement->Attribute("v")));
                                        vertexElement = vertexElement->NextSiblingElement("vertex");
					i++;
                                }
                                triangleElement = triangleElement->NextSiblingElement("triangle");
                        }
                }
        }
	
	headerData.triangleCount = triangleList.GetTotalElements();
	
	FILE* fp; // FILE object.
	fp = fopen(out, "wb"); // Write using binary format
	if (fp == NULL) {
		ErrorOut("Could not create file.");
	}
	fwrite(&versionData, sizeof(ModelVersion), 1, fp); // Write file version.
	
	WriteString(headerData.title, fp);
	WriteString(headerData.description, fp);
	WriteString(headerData.author, fp);
	WriteString(headerData.defaultMaterialName, fp);
	WriteString(headerData.defaultMaterialPath, fp);
	fwrite(&headerData.triangleCount, sizeof(unsigned int), 1, fp);
	
	float posx = 0;
	float posy = 0;
	float posz = 0;
	float normx = 0;
	float normy = 0;
	float normz = 0;
	float u = 0;
	float v = 0;
	
	triangleList.Iterate(true);
	while(triangleList.Iterate() != NULL) {
		for (i=0; i<3; i++) {
			posx = triangleList.GetCurrent()->m_vertices[i]->m_pos->Get(0);
			posy = triangleList.GetCurrent()->m_vertices[i]->m_pos->Get(1);
			posz = triangleList.GetCurrent()->m_vertices[i]->m_pos->Get(2);
			normx = triangleList.GetCurrent()->m_vertices[i]->m_normal->Get(0);
			normy = triangleList.GetCurrent()->m_vertices[i]->m_normal->Get(1);
			normz = triangleList.GetCurrent()->m_vertices[i]->m_normal->Get(2);
			u = triangleList.GetCurrent()->m_vertices[i]->m_texCoords->Get(0);
			v = triangleList.GetCurrent()->m_vertices[i]->m_texCoords->Get(1);
			fwrite(&posx, sizeof(float), 1, fp); // posx.
			fwrite(&posy, sizeof(float), 1, fp); // posy.
			fwrite(&posz, sizeof(float), 1, fp); // posz.
			fwrite(&normx, sizeof(float), 1, fp); // normx.
			fwrite(&normy, sizeof(float), 1, fp); // normy.
			fwrite(&normz, sizeof(float), 1, fp); // normz.
			fwrite(&u, sizeof(float), 1, fp); // u.
			fwrite(&v, sizeof(float), 1, fp); // v.
		}
	}
	fclose(fp);
}